package com.gjy.util;

import org.openjdk.jol.info.ClassLayout;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Field;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2022-12-15 13:51:07
 */
public final class ObjectUtil {

    public static <T> String bytes(T t) {
        return ClassLayout.parseInstance(t).toPrintable();
    }

    public static <T> T deepClone(T t) {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             ObjectOutputStream oos = new ObjectOutputStream(baos);

             ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
             ObjectInputStream ois = new ObjectInputStream(bais)
        ) {
            oos.writeObject(t);
            return ((T) ois.readObject());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 判断一个对象的某个字段是否为空
     *
     * @param t     对象
     * @param field 字段
     * @param <T>   任意对象
     * @return 为空返回true
     */
    public static <T> boolean isNull(T t, String field) {
        if (null == t) {
            return true;
        }
        try {
            Class<?> clazz = t.getClass();
            Field df = clazz.getDeclaredField(field);
            df.setAccessible(true);
            return df.get(t) == null;
        } catch (Exception e) {
            return false;
        }
    }

}
